<?php
/**
 * 卡券
 */
namespace Common\Model;
use Think\Exception;
use Think\Model;

class CouponModel extends BaseModel
{
	private static $instance=null;
	public static function getInstance(){
		if(!self::$instance){
			self::$instance=M('card_base_info',null,DB_MAIN_CFG);
		}
		return self::$instance;
	}



	const CARD_CREATE_BATCH_LIMIT_NUM		= 1000;//单批生成数量上限

	//卡券类型
	const CARD_TYPE_GROUPON_CARD 			= 'GROUPON';//团购卷 GROUPON
	const CARD_TYPE_CASH_CARD 				= 'CASH';//代金卷 CASH
	const CARD_TYPE_DISCOUNT_CARD 			= 'DISCOUNT';//折扣卷 DISCOUNT
	const CARD_TYPE_GIFT_CARD				= 'GIFT';//礼品券 GIFT
	const CARD_TYPE_GENERAL_COUPON_CARD 	= 'GENERAL_COUPON';//优惠卷 GENERAL_COUPON

	//关于微信卡券预存code
	const WEIXIN_DEPOSIT_NONE				= 0;//需要预存，但未全部预存
	const WEIXIN_DEPOSIT_ALL				= 1;//需要预存，且已全部预存   本类券号核销，删除等需要进行双向同步
	const WEIXIN_DEPOSIT_NONEED				= 2;//不需要预存

	const WEIXIN_STOCK_REMIND				=1;//微信卡券库存报警
	const WEIXIN_USE_CUSTOM_CODE			=1;//微信卡券使用自定义code，在此情况下有两种情形，1预存到微信，2与未预存到微信

	public static function getCardType(){
		return array(
			self::CARD_TYPE_GROUPON_CARD 		=> '团购卷',//团购卷 GROUPON
			self::CARD_TYPE_CASH_CARD 			=> '代金卷',//代金卷 CASH
			self::CARD_TYPE_DISCOUNT_CARD 		=> '折扣卷',//折扣卷 DISCOUNT
			self::CARD_TYPE_GIFT_CARD			=> '礼品券',//礼品券 GIFT
			self::CARD_TYPE_GENERAL_COUPON_CARD => '优惠卷'//优惠卷 GENERAL
		);
	}

	
	
	//积分兑换 卡券的日期选择
	const CARD_COUSTOM_DAY = 1;//自定义日期
	const CARD_FIXED_DAY = 2;//固定日期

	//卡券号使用状态
	const CODE_STATUS_DEFAULT 	= 0;//券号默认状态，库存中
	const CODE_STATUS_RECEIVED 	= 1;//被领取
	const CODE_STATUS_USED 		= 2;//已经使用
	const CODE_STATUS_OUTDATE 	= 3;//过期
	const CODE_STATUS_DELETE 	= 4;//删除
	const CODE_STATUS_SEND 		= 5;//被发出，但未被领取


	//卡券核销来源
	const CARD_CONSUME_FROM_MYSELF = 1;//自主核销
	const CARD_CONSUME_FROM_ADMIN 	= 2;//后台核销
	const CARD_CONSUME_FROM_WEIXIN 	= 3;//微信核销

	//卡券可使用平台枚举
	const CARD_PLATFORM_ALL		= 0;//全部类型仅用于查询
	const CARD_PLATFORM_BOTH	= 1;//自平台与微信打通
	const CARD_PLATFORM_WEIXIN	= 2;//仅微信
	const CARD_PLATFORM_STARJOY	= 3;//仅自平台,星悦

	public static function getPlatform(){
		return array(
			//self::CARD_PLATFORM_ALL		=> '全部类型仅用于查询',
			//self::CARD_PLATFORM_WEIXIN	=> '仅微信',
			self::CARD_PLATFORM_STARJOY	=> '仅自平台',
			//self::CARD_PLATFORM_BOTH		=> '自平台与微信打通'
		);
	}

	/**
	 * 获取卡券的所有使用状态
	 * Author: shijy
	 * @return array
	 */
	public static function getCardUseStatus()
	{
		return array(
			self::CODE_STATUS_DEFAULT	=>'库存中',
			self::CODE_STATUS_SEND	=>'被发出，未被领取',
			self::CODE_STATUS_RECEIVED=>'已领取，未使用',
			self::CODE_STATUS_USED	=>'已使用',
			self::CODE_STATUS_OUTDATE	=>'过期',
			self::CODE_STATUS_DELETE	=>'删除'
		);
	}

	/**
	 * 获取指定卡券的基础信息
	 * Author: shijy
	 * @param $cardID
	 * @return array
	 */
	public static function getCardBaseInfo($cardID){
		$dataSuccess = array('status' => self::SUCCESS, 'msg' => '成功');
		$dataFailure = array('status' => self::FAILURE, 'msg' => '无效参数');
		$data=self::getInstance()->where("id={$cardID}")->find();
		if(!$data){
			$dataFailure['msg']='不存在指定类型卡券信息！';
		}
		$dataSuccess['data']=$data;
		return $dataSuccess;
	}

	/**
	 * 根据微信卡号获得本平台卡号
	 * Author: shijy
	 * @param $wxCardID
	 * @return array
	 */
	public static function getCardIDByWxCardID($wxCardID){
		$dataSuccess = array('status' => self::SUCCESS, 'msg' => '成功');
		$dataFailure = array('status' => self::FAILURE, 'msg' => '无效参数');
		$cardID=self::getInstance()->where("weixinId='{$wxCardID}'")->getField('id');
		if(!$cardID){
			$dataFailure['msg']='没有对应活动';
			return $dataFailure;
		}
		$dataSuccess['cardID']=$cardID;
		return $dataSuccess;
	}

	/**
	 * 发送卡券给指定用户--仅自平台
	 * Author: shijy
	 */
	public static function sendCard_starjoy($cardTypeId, $uid, $beginTime=0,$endTime=0)
	{
		$dataSuccess = array('status' => self::SUCCESS, 'msg' => '成功');
		$dataFailure = array('status' => self::FAILURE, 'msg' => '无效参数');

		//先获取一张没有被使用卡券
		$card_code = M('card_code', null, DB_MAIN_CFG);//卡券列表
		$item = $card_code
			->where('status = 0 and uid=0 and cardId=' . $cardTypeId)
			->find();
		if (!$item) {
			$dataFailure['msg'] = '卡券库存不足';
			return $dataFailure;
		}


		//更新卡券信息
		$card_list_data = array(
			'uid' => $uid,
			'status' => self::CODE_STATUS_RECEIVED,
			'receiveTimestamp' => time(),

		);
		if($beginTime>0){
			$card_list_data['beginTimestamp']=$beginTime;
		}
		if($endTime>0){
			$card_list_data['endTimestamp']=$endTime;
		}
		$card_code->where('id=' . $item['id'])->save($card_list_data);

		$dataSuccess['code'] = $item['code'];
		$dataSuccess['password'] = $item['password'];
		$dataSuccess['platformSwitch']	= CouponModel::CARD_PLATFORM_STARJOY;
		$dataSuccess['cardId']	= $cardTypeId;
		return $dataSuccess;

	}


	/**
	 * 当前正在使用的
	 * 发送卡券给指定用户--自平台与微信互通版
	 * Author: shijy
	 * @param $cardTypeId 本平台卡券编号
	 * @param $uid  获得者用户编号
	 * @param int $objType  卡券绑定的对象类型
	 * @param int $objId  卡券绑定的对象编号
	 * @return array
	 * @throws Exception
	 */
	public static function sendCard_both($cardTypeId,$uid,$objType=0,$objId=0){
		$dataSuccess = array('status' => self::SUCCESS, 'msg' => '成功');
		$dataFailure = array('status' => self::FAILURE, 'msg' => '无效参数');
		$cardBaseInfo=self::getCardBaseInfo($cardTypeId);
		if($cardBaseInfo['status']!=0){
			return $cardBaseInfo;
		}
		$cardBaseInfo=$cardBaseInfo['data'];

		///库存是否报警
		if($cardBaseInfo['weixinStockRemind']==self::WEIXIN_STOCK_REMIND){
			$dataFailure['msg'] = '卡券库存不足';
			return $dataFailure;
		}


		///取code
		$updateCode=false;
		if($cardBaseInfo['weixinUseCustomCode']==self::WEIXIN_USE_CUSTOM_CODE){
			//预存
			if($cardBaseInfo['weixinDeposit']==self::WEIXIN_DEPOSIT_NONEED){
				//先获取一张没有被使用卡券
				$card_code = M('card_code', null, DB_MAIN_CFG);//卡券列表

				$where='status = 0 and uid=0 and cardId=' . $cardTypeId;
				if($objType==0){
					//throw new Exception('未实现');
				} else{
					$where .= ' and objType ='.$objType;
				}
				if($objId>0){
					$where .=' and objID ='.$objId;
				}
				$code = $card_code->where($where)->getField('code');
				if (!$code) {
					$dataFailure['msg'] = '卡券库存不足';
					return $dataFailure;
				}
				$updateCode=true;
			}else{
				$code='';
			}
		}else{
			$code='';
		}

		$userBaseInfo=UserModel::getUser($uid);
		if($userBaseInfo['status']!=0){
			return $userBaseInfo;
		}
		$openID=$userBaseInfo['data']['openid'];

		$cardExtReturn=WeixinModel::getCardExt($cardBaseInfo['weixinId'],$openID,$code);
		if($cardExtReturn['status']!=0){
			return $cardExtReturn;
		}
		if ($updateCode){
			M('card_code',null,DB_MAIN_CFG)->where("code='{$code}' and cardId={$cardBaseInfo['id']}")->save(
				array(
					'status'=>CouponModel::CODE_STATUS_SEND,
					'uid'=>$uid
				));
		
		
		}

		//减库存
		self::minusStock($cardBaseInfo['id']);

		$cardExt=$cardExtReturn['cardExt'];
		$dataSuccess['platformSwitch']	= CouponModel::CARD_PLATFORM_BOTH;
		$dataSuccess['cardId']	= $cardTypeId;
		$dataSuccess['code'] 	= $code;
		//用于微信jsapi调用
		$dataSuccess['cardExt'] = $cardExt;
		$dataSuccess['wxCardID'] = $cardBaseInfo['weixinId'];
		return $dataSuccess;
	}

	/**
	 * 库存减少
	 * 卡券库存减少无视用户是否真的领取
	 * Author: shijy
	 * @param $cardid 卡号
	 * @param $minusNum 扣减数量，默认为1
	 */
	public static function minusStock($cardid,$minusNum=1){
		self::getInstance()->where("id={$cardid}")->setDec('stock',$minusNum);//库存减一
	}

	/**
	 * 获取我的处于有效期内的卡券
	 * Author: shijy
	 * @param $uid
	 * @param $page
	 * @param $pageSize
	 * @return array
	 */
	public static function getMyUserfullCardList($uid,$page,$pageSize){
	 	$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$card_code 	= M('view_user_card',null,DB_MAIN_CFG);
		$now 		= time();
		$where 		= 'uid='.$uid.' and status in('.self::CODE_STATUS_RECEIVED.','.self::CODE_STATUS_SEND.') and endTimestamp >'.$now;

		$distinctCount = $card_code->where($where)->count('distinct baseCardId,beginTimestamp,endTimestamp,bindInfo');
		$dataSuccess['total'] 		= array_keys($distinctCount)[0];//获取数据总条数
		$dataSuccess['page'] 		= max($page,1);//返回当前页
		$dataSuccess['totalPage'] 	= ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] 	= $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset = ($dataSuccess['page']-1) * $pageSize;

		$list 	= $card_code
			->where($where)
			->group('`table`,baseCardId,beginTimestamp,endTimestamp,bindInfo')
			->field('baseCardId,`table`,min(status) as status,min(id) as id,min(cardTitle) as cardTitle,endTimestamp,min(type) as type,bindInfo,min(`code`) as `code`,min(img) as img,count(*) as totalNum')
			->limit($offset,$pageSize)
			->order(" endTimestamp ASC ")
			->select();

		if(count($list)>0){
			$company=self::getCardImgKv();
			foreach($list as $k=>$v){
				if(!$v['img']){
					$list[$k]['img']=$company[$v['baseCardId']];
				}
			}
		}

		$dataSuccess['data'] = $list;
		return $dataSuccess;
	}

	/**
	 * 返回基础商户信息
	 * Author: shijy
	 * @return array
	 */
	public static function getAllBaseRestaurant(){
		$company=M('s_restaurant',null,DB_MAIN_CFG)->field('id,restaurantName,photo')->select();
		$res=array();
		foreach($company as $one){
			$res[$one['id']]=$one;
		}
		unset($company);
		return $res;
	}


	/**
	 * 根据商户编号获取商户信息
	 * Author: shijy
	 * @param $restaurantID
	 * @return mixed
	 */
	public static function getOneRestaurant($restaurantID){
		return M('s_restaurant',null,DB_MAIN_CFG)->where('id='.$restaurantID)->field('id,restaurantName,photo')->find();
	}
	/**
	 * 根据商户编号获取商户信息
	 * Author: shijy
	 * @param $restaurantID
	 * @return mixed
	 */
	public static function getOneStore($storeID){
		return M('s_store',null,DB_MAIN_CFG)->where('id='.$storeID)->field('id,storeName')->find();
	}

	/**
	 * 获取我的历史卡券
	 * Author: shijy
	 * @param $uid
	 * @param $page
	 * @param $pageSize
	 * @return array
	 */
	public static function getMyHistoryList($uid,$page,$pageSize){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$now=time();
		$where ='uid='.$uid .' and  (endTimestamp <'.$now.' or  status ='.self::CODE_STATUS_USED.')';
		$card_code = M('view_user_card',null,DB_MAIN_CFG);

		$dataSuccess['total'] = $card_code->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = max($page,1);//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset = ($dataSuccess['page']-1)*$pageSize;

		$list = $card_code
			->where($where)
			->order('addTime DESC')
			->limit($offset,$pageSize)
			->select();

		//echo $card_code->getLastSql();

		if(count($list)>0){
			$company=self::getCardImgKv();
			foreach($list as $k => $value){
				//判断是否过期的
				if($list[$k]['endTimestamp'] < $now && $value['status']!=self::CODE_STATUS_USED){
					$list[$k]['status'] = self::CODE_STATUS_OUTDATE;
				}

				if(!$value['img']){
					$list[$k]['img']=$company[$value['baseCardId']];
				}
			}
		}
		$dataSuccess['data'] = $list;
		return $dataSuccess;
	}


	/**
	 *检查用户未领取的券号
	 * Author: shijy
	 * @param $uid
	 * @return array|mixed
	 */
	public static function checkNoReceiveWeixinCode($uid){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$status=self::CODE_STATUS_SEND;
		$unReceiveCode=M('card_code',null,DB_MAIN_CFG)->where("uid={$uid} and weixinBind=1 and status={$status}")->find();

		if(!$unReceiveCode){
			$dataFailure['msg']='没有未领取的微信卡券';
			return $dataFailure;
		}

		$cardBaseInfo=CouponModel::getCardBaseInfo($unReceiveCode['cardId']);
		if($cardBaseInfo['status']!=0){
			return $cardBaseInfo;
		}
		$cardBaseInfo=$cardBaseInfo['data'];

		$userBaseInfo=UserModel::getUser($uid);
		if($userBaseInfo['status']!=0){
			return $userBaseInfo;
		}
		$openId=$userBaseInfo['data']['openid'];
		return WeixinModel::getCardExt($cardBaseInfo['weixinId'],$openId,$unReceiveCode['code']);
	}

	/**
	 * 根据卡券号获取卡券信息
	 * Author: shijy
	 * @param $code
	 * @return array
	 */
	public static function getCodeInfo($code){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(strlen($code)<12){
			$dataFailure['msg']='卡券号长度错误！';
			return $dataFailure;
		}
		$codeInfo=M('card_code',null,DB_MAIN_CFG)->where("code='{$code}'")->find();
		if(!$codeInfo){
			$dataFailure['msg']='卡券号不存在';
			return $dataFailure;
		}

		$codeInfo['restaurantName']='';
		if($codeInfo['restaurantId']!=0){
			$restaurantName=M('s_restaurant',null,DB_MAIN_CFG)->where('id='.$codeInfo['restaurantId'])->getField('restaurantName');
			$codeInfo['restaurantName']=$restaurantName;
		}

		$dataSuccess['data']=$codeInfo;



		return $dataSuccess;
	}


	/**
	 * 随机生成12位的卡券号 存入数据库
	 * 算法描述 卡券号 12位
	 * 卡券编号5位     C
	 * 生成批次4位     B
	 * 卡券随机序列号3位  S
	 * 单批次限生成至多999张卡
	 *  $S[0].$C[4].$C[0].$B[0].$B[3].$C[1].$C[3].$B[1].$B[2].$S[1].$C[2].$S[2];
	 * Author: shijy
	 * @param $cardId 对应卡券信息表的 id
	 * @param $stock
	 * @param $batch 批次
	 * @param int $bindWeixin 绑定微信，1是，0否
	 * @return array
	 */
	public static function createRandomCodeList($cardId,$stock,$batch,$bindWeixin=0)
	{
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$codeM = M('card_code', null, DB_MAIN_CFG);

		$haveCount=$codeM->where("cardId={$cardId}")->count();
		if($haveCount>=$stock){
			$dataFailure['msg']='生成的卡券数已经达到要求数量';
			return $dataFailure;
		}
		$leftStock	= $stock -$haveCount;
		$createLimit=min($leftStock,self::CARD_CREATE_BATCH_LIMIT_NUM);

		//根据cardId 如果不满5位则自动向左补5位
		$C          = str_pad(strval($cardId), 5, 0, STR_PAD_LEFT);  //卡号card
		$B          = str_pad(strval($batch), 4, 0, STR_PAD_LEFT);   //批号batch

		$cardBaseM=self::getInstance();
		$cardBaseInfo=$cardBaseM->where('id='.$cardId)->field('title,restaurantId,storeId')->find();
		if(!$cardBaseInfo){
			$dataFailure['msg']='指定卡券不存在';
			return $dataFailure;
		}

		$dataList = array();
		$now=time();
		//根据库存生成相对应的卡券id

		$tmpArray=range(0,999);
		shuffle($tmpArray);
		for($i=0;$i<$createLimit;$i++){
			$tmpNum=$tmpArray[$i];
			$S =str_pad($tmpNum, 3, 0, STR_PAD_LEFT);//券序列号，serial number
			//优化细节
			$code = $S[0].$C[4].$C[0].$B[0].$B[3].$C[1].$C[3].$B[1].$B[2].$S[1].$C[2].$S[2];
			$dataList[] = array(
				'cardTitle' 		=> $cardBaseInfo['title'],
				'createTimestamp' 	=> $now,
				'restaurantId' 		=> $cardBaseInfo['restaurantId'],
				'storeId'			=> $cardBaseInfo['storeId'],
				'cardId'   			=> $cardId,
				'status' 			=> self::CODE_STATUS_DEFAULT,
				'weixinBind'		=> $bindWeixin,
				'code' 				=> $code
			);
		}

		//批量插入数据库
		$result = $codeM->addAll($dataList);
		if($result==false){
			$dataFailure['msg'] = $codeM->getError();
			return $dataFailure;
		}

		//更改生成批数
		$cardBaseM->where('id='.$cardId)->setInc('batchNum');
		if($createLimit==$leftStock){
			$dataSuccess['finish']=1;
		}else{
			$dataSuccess['finish']=0;
		}
		return $dataSuccess;
	}



	/**
	 *上传微信卡券,当返回状态为失败，且是全部已经提交的才可以结束。返回成功仅表明本次提交是成功的
	 * Author: shijy
	 * @param $cardId
	 * @return array|mixed
	 */
	public static function depositWexinCard($cardId){
		$dataSuccess 	= array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure 	= array('status'=>self::FAILURE,'msg'=>'无效参数');
		$cardBaseM		= self::getInstance();
		$cardBase		= $cardBaseM->where("id={$cardId}")->field('weixinId,platformSwitch')->find();
		if(!$cardBase){
			$dataFailure['msg']='没有对应的基础卡券';
			return $dataFailure;
		}
		if($cardBase['platformSwitch']!=CouponModel::CARD_PLATFORM_BOTH && $cardBase['platformSwitch']!=CouponModel::CARD_PLATFORM_WEIXIN){
			$dataFailure['msg']='不是微信卡券';
			return $dataFailure;
		}

		$codeM=M('card_code',null,DB_MAIN_CFG);
		$codeList=$codeM->where("cardId={$cardId} and weixinDeposit=0")->limit(WeixinTicketModel::ONCE_DEPOSIT_CODE_MAX_NUM)->getField('code',true);
		if(count($codeList)<1){
			$dataFailure['finish']=1;
			$dataFailure['msg']='所有券号均已上传微信！';
			$cardBaseM->where("id={$cardId}")->setField('weixinDeposit',CouponModel::WEIXIN_DEPOSIT_ALL);
			return $dataFailure;
		}
		$dataSuccess['finish']=0;

		$return = WeixinTicketModel::depositCode($cardBase['weixinId'],$codeList);
		if($return['status']!=0){
			return $return;
		}

		if($return['data']['succ_code']==0){
			$dataFailure['msg']='上传卡券失败';
			return $dataFailure;
		}elseif($return['data']['succ_code']==count($codeList)){//没有导入失败的
			$where= 'code in ("'.implode('","',$codeList).'")';
			$changeVal=count($codeList);
		}else{
			$return=WeixinTicketModel::checkDepositCode($cardBase['weixinId'],$codeList);
			$where= 'code in ("'.implode('","',$return['data']['exist_code']).'")';
			$changeVal=count($return['data']['exist_code']);
		}

		//修改微信上的卡券库存
		$modifyResult=WeixinTicketModel::modifyStock($cardBase['weixinId'],$changeVal);
		if($modifyResult['status']['data']['errcode']==0){
			$codeM->where($where)->setField('weixinDeposit',1);
			$dataSuccess['msg']='本次成功上传：'.$changeVal;
			return $dataSuccess;
		}else{
			$dataFailure['msg']='更新库存数量失败！！';
			return $dataFailure;
		}
	}



	/**
	 *用户自主核销卡券
	 * Author: shijy
	 * @param $uid
	 * @param $code
	 * @param $storeId
	 * @throws Exception
	 */
	public static function selfConsumeCode($uid,$code,$storeId){
		throw new Exception("未实现函数");
	}
	/**
	 * 商户核销卡券
	 * Author: shijy
	 * @param $uid
	 * @param $code
	 * @return array
	 */
	public static function shopConsumeCode($uid,$code){
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');


		$verificationReturn=CouponModel::getVerificationByUid($uid);

		if($verificationReturn['status']!=0){
			$dataFailure['msg']='核销者并非核销员，不能进行本操作';
			return $dataFailure;
		}

		$verificationId 			= $verificationReturn['data']['id'];
		$verificationStoreId		= $verificationReturn['data']['storeId'];
		$verificationRestaurantId	= $verificationReturn['data']['restaurantId'];
		unset($verificationReturn);
		return self::consumeCode(self::CARD_CONSUME_FROM_WEIXIN,$verificationId,$code,$verificationStoreId,$verificationRestaurantId);
	}


	/**
	 * 核销卡券号
	 * Author: shijy
	 * @param $consumeFrom 核销来源
	 * @param $verificationId 核销工号
	 * @param $code 卡券号
	 * @param $verificationStoreId 核销者门店
	 * @param storeId 所属门店
	 * @param $verificationRestaurantId 核销者商户编号
	 * @return array
	 */
	public static function consumeCode($consumeFrom,$verificationId,$code,$verificationStoreId,$verificationRestaurantId){
		$enabled=self::checkCodeConsumeAble($code,$verificationStoreId);
		if($enabled['status']!=0){
			return $enabled;
		}

		//更改卡券的使用状态
		$codeUpdate=array(
			'status'=>CouponModel::CODE_STATUS_USED,
			'consumeTime'=>time(),
			'consumeType'=>$consumeFrom,
			'verificationId'=>$verificationId,
			'verificationStoreId'=>$verificationStoreId,
//			'storeId'=>$verificationStoreId,
			'restaurantId'=>$verificationRestaurantId
		);
		M('card_code',null,DB_MAIN_CFG)->where('code='.$code)->save($codeUpdate);
		M('s_verification',null,DB_MAIN_CFG)->where("id={$verificationId}")->setInc('verifyNum');


		//如果是微信卡券,同步也进行核销
		$codinfo=self::getCodeInfo($code);
		$cardid=$codinfo['data']['cardId'];
		$cardInfo=self::getCardBaseInfo($cardid);
		if($cardInfo['data']['platformSwitch']==CouponModel::CARD_PLATFORM_BOTH){
			WeixinTicketModel::consume($cardInfo['data']['weixinId'],$code);
		}
		

		$enabled['msg'] = '核销成功';
		return $enabled;
	}


	/**
	 * 检查卡券可否被核销
	 * Author: shijy
	 * @param $code
	 * @param $verificationId 核销员编号
	 * @param $verificationStoreId  核销门店
	 * @param $verificationRestaurantId 核销商户
	 * @return array
	 */
	public static function checkCodeConsumeAble($code,$verificationStoreId,$verificationRestaurantId){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$codeReturn=self::getCodeInfo($code);
		if($codeReturn['status']!=0){
			return $codeReturn;
		}
		$codeinfo=$codeReturn['data'];
		//判断该卡券是否已经被使用
		if($codeinfo['status'] != CouponModel::CODE_STATUS_RECEIVED && $codeinfo['status'] !=CouponModel::CODE_STATUS_SEND){
			$dataFailure['msg'] = '该卡券状态不可被核销';
			return $dataFailure;
		}

		//获取该卡券的有效期
//		if(empty($codeinfo['beginTimestamp'])){
//			$endTime = $codeinfo['receiveTimestamp'] + $codeinfo['fixedBeginTerm'] * UtilsModel::ONE_DAY + $codeinfo['fixedTerm'] * UtilsModel::ONE_DAY;
//		}else{
//			$endTime = $codeinfo['endTimestamp'];
//		}

		if($codeinfo['endTimestamp'] < time()){
			$dataFailure['msg'] = '卡券已过期';
			return $dataFailure;
		}


		$cardReturn=self::getCardBaseInfo($codeinfo['cardId']);
		if($codeReturn['status']!=0){
			return $codeReturn;
		}
		$cardInfo=$cardReturn['data'];
		$availableDay=$cardInfo['availableDay'];

		$time = getdate(time());
		$day = $time['wday'];
		$availableDayS=explode(',',$availableDay);
		if(!in_array($day,$availableDayS)){
			$dataFailure['msg'] = '今日无法使用该卡券';
			return $dataFailure;
		}

		$NO_LIMIT=0;
		do{
			if($verificationRestaurantId==$NO_LIMIT){
				//超级核销号
				break;
			}

			if($cardInfo['restaurantId']==$NO_LIMIT && $cardInfo['storeId']==$NO_LIMIT){
				//卡券无限制
				break;
			}


			if($cardInfo['restaurantId']!=$NO_LIMIT && $cardInfo['storeId']==$NO_LIMIT){
				//限商户，不限门店
				if ($verificationRestaurantId != $cardInfo['restaurantId']){
					$dataFailure['msg'] = '不能核销其他商户的卡券';
					return $dataFailure;
				}
				break;
			}
			if($cardInfo['storeId']!=$NO_LIMIT){
				$card_storeId = explode(',', $cardInfo['storeId']);
				if (!in_array($verificationStoreId, $card_storeId)) {
					$dataFailure['msg'] = '该门店无法使用并核销该卡券';
					return $dataFailure;
				}
			}


		}while(false);

		$dataSuccess['msg']='可以核销';
		return $dataSuccess;
	}


	/**
	 * 根据前台用户编号获取对应核销员信息
	 * Author: shijy
	 * @param $uid
	 * @return array
	 */
	public static function getVerificationByUid($uid){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$userReturn=UserModel::getUser($uid);
		if($userReturn['status']!=0){
			$dataFailure['status']=2;
			$dataFailure['msg']='用户未绑定手机号，无法确认身份';
			return $dataFailure;
		}


		$bindPhone=$userReturn['data']['bindPhone'];
		if(!$bindPhone || !(filedPreMatch('phone', $bindPhone))) {
			$dataFailure['status']=2;
			$dataFailure['msg']='用户未绑定手机号，无法确认身份';
			return $dataFailure;
		}

		$result=M('s_verification',null,DB_MAIN_CFG)->where("phone='{$bindPhone}'")->find();
		if(!$result){
			$dataFailure['msg']='找不到对应的核销员';
			return $dataFailure;
		}
		$dataSuccess['data']=$result;
		return $dataSuccess;
	}


	/**
	 * 获取卡券键值数组
	 * Author: shijy
	 * @return array
	 */
	public static function getCardKv(){
		$kv=self::getInstance()->getField('id,title',true);
		return $kv;
	}

	/**
	 * 获取卡券图片键表
	 * Author: shijy
	 * @return array
	 */
	public static function getCardImgKv(){
		$arr=self::getInstance()->getField('id,photo',true);
		return $arr;
	}

	public static function getCodeList($ownerUid,$cardId,$verificationId,$codeStutus=-1,$page=1,$pageSize=30){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$where='1';
		if ($cardId>0){
			$where .=' and cardId='.$cardId;
		}

		if($verificationId){
			$where .=' and verificationId='.$verificationId;
		}

		if ($codeStutus>=0){
			$where .=' and status='.self::CODE_STATUS_USED;
		}

		if($ownerUid>0){
			$where .=' and uid='.$ownerUid;
		}

		if(!$page){
			$page=1;
		}
		$M=M("card_code",null,DB_MAIN_CFG);
		$rowCount=$M->where($where)->count();

		$pageCount=max(1,ceil($rowCount/$pageSize));
		$page=min(max($page,1),$pageCount);
		$offset=($page-1) * $pageSize;

		$list=$M->where($where)
			->order('consumeTime DESC,receiveTimestamp DESC')
			->limit($offset,$pageSize)
			->select();
		foreach ($list as $k=>$v){
			$tmp=str_split($v['code'],4);
			$list[$k]['showCode']=implode(' ',$tmp);
		}

		if(count($list)>0 && !$ownerUid && $codeStutus!=self::CODE_STATUS_DEFAULT){
			//不指定用户，且状态不为默认，则查询对应用户
				$uids=array();
				foreach ($list as $one){
					if($one['uid']>0){
						$uids[]=$one['uid'];
					}
				}
				if(count($uids)>0){
					$uidstr=implode(',',$uids);
					$users=M('u_user_base',null,DB_MAIN_CFG)->where("uid in ({$uidstr})")->field('uid,nickname')->select();

					foreach ($list as $k=>$one){
						if(!$one['uid']){
							$list[$k]['nickname']='';
						}
						else{
							foreach ($users as $u){
								if($u['uid']==$one['uid']){
									$list[$k]['nickname']=$u['nickname'];
									break;
								}
							}
						}
					}
				}
		}
		///////////////////////////////////////////////////
		$dataSuccess['total']	=$rowCount;
		$dataSuccess['totalPage']=$pageCount;
		$dataSuccess['page']	=$page;
		$dataSuccess['nextPage'] = $page >= $pageCount ? 0 : 1;//是有有下一页
		$dataSuccess['list']	=$list;
		return $dataSuccess;
	}

	//获取可用卡券数量
	public static function getAvailableCardNum($cardId){
		$count = M('card_code',null,DB_MAIN_CFG)->where("cardId={$cardId} and status=".self::CODE_STATUS_DEFAULT." and objType=".OBJ_TYPE_ALL)->count();
		return $count;
	}
	
}